package com.hs.common.core.domain;

import com.hs.common.core.constant.Constants;
import lombok.Data;

import java.io.Serializable;

/**
 * 响应信息主体
 */
@Data
public class Result<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 成功
     */
    public static final int SUCCESS = Constants.SUCCESS;

    /**
     * 失败
     */
    public static final int FAIL = Constants.FAIL;

    private int code;

    private String msg;

    private T data;

    public static <T> Result<T> ok() {
        return restResult(SUCCESS, null, null);
    }

    public static <T> Result<T> ok(T data) {
        return restResult(SUCCESS, null, data);
    }

    public static <T> Result<T> ok(T data, String msg) {
        return restResult(SUCCESS, msg, data);
    }

    public static <T> Result<T> fail() {
        return restResult(FAIL, null, null);
    }

    public static <T> Result<T> fail(String msg) {
        return restResult(FAIL, msg, null);
    }

    public static <T> Result<T> fail(T data) {
        return restResult(FAIL, null, data);
    }

    public static <T> Result<T> fail(T data, String msg) {
        return restResult(FAIL, msg, data);
    }

    public static <T> Result<T> fail(int code, String msg) {
        return restResult(code, msg, null);
    }

    private static <T> Result<T> restResult(int code, String msg, T data) {
        Result<T> apiResult = new Result<>();
        apiResult.setCode(code);
        apiResult.setMsg(msg);
        apiResult.setData(data);
        return apiResult;
    }

    public static <T> Boolean isError(Result<T> ret) {
        return !isSuccess(ret);
    }

    public static <T> Boolean isSuccess(Result<T> ret) {
        return Result.SUCCESS == ret.getCode();
    }
}
